import { getRoleList } from '@/apis/accessManagement/role'
import { getStaffInfo } from '@/apis/accessManagement/staff'
import { addStaff } from '@/apis/accessManagement/staff'
import { updateStaffInfo } from '@/apis/accessManagement/staff'
import { useRef,useState,useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import layout from './index.module.scss'
import uploadPhotoIcon from '@/assets/upload-photo-icon.png'
import reactSvg from '@/assets/Avatar_default.png'
import { Button, Tabs, Form, Input, Select, Switch,Flex,message,Spin } from 'antd'
import { useLocation } from 'react-router-dom'
import md5 from 'js-md5'
import dayjs from 'dayjs'

const StaffDetail = () => {
    const {TextArea} = Input
    const [form] = Form.useForm()
    const navigate = useNavigate()
    const location = useLocation()
    const query = new URLSearchParams(location.search)
    const state = query.get('state')
    const userID = query.get('userId')
    const [showPwd, setShowPwd] = useState(false)
    const [loading, setLoading] = useState(false)
    const [messageApi, contextHolder] = message.useMessage()
    const [options, setOptions] = useState([])
    const [roleValue, setRoleValue] = useState(null);
    const [defaultAccount, setDefaultAccount] = useState('')
    const [defaultNickName, setDefaultNickName] = useState('')
    const [defaultUserStatus, setDefaultUserStatus] = useState(true)
    const [defaultUserStatusTxt, setDefaultUserStatusTxt] = useState(null)
    const [defaultUserRole, setDefaultUserRole] = useState('')
    const [defaultUserRoleName, setDefaultUserRoleName] = useState('')
    const [latestLoginTime, setLatestLoginTime] = useState('')
    const [handleRoleId, setHandleRoleId] = useState(null)

    const roleChange = (value:any,item:any) => {
        console.log('checked---', value);
        setRoleValue(value);
        setHandleRoleId(item.roleId)
    };

    // 查询单个员工
    const searchStaff = async () => {
        setLoading(true)
        try {
            const response = await getStaffInfo({
                userId: userID,
            });
            // const response = await getRoleList();
            if (response || response.data) {
                if (response?.errCode === 0) {
                    message.success('员工信息获取成功')
                    const userAccount = response.data.account;
                    const userNickname = response.data.nickname;
                    const userStatusTxt = response.data.status;
                    const userStatus = response.data.status === 1?true:false;
                    const userRole = response.data.roleCode;
                    const userRoleName = response.data.roleName;
                    const userRoleId = response.data.roleId;
                    const latestLoginTime = response.data.latestLoginTime;
                    setDefaultAccount(userAccount); 
                    setDefaultNickName(userNickname); 
                    setDefaultUserStatus(userStatus); 
                    setDefaultUserStatusTxt(userStatusTxt); 
                    setDefaultUserRole(userRole); 
                    setDefaultUserRoleName(userRoleName); 
                    setHandleRoleId(userRoleId); 
                    setLatestLoginTime(dayjs(latestLoginTime).format('YYYY-MM-DD HH:mm:ss') ); 
                    searchRole()
                } else {
                    message.error(`获取数据失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // 查询角色
    const searchRole = async () => {
        setLoading(true)
        try {
            const response = await getRoleList();
            if (response || response.data) {
                if (response?.errCode === 0) {
                    const formattedOptions = response.data.roles.map((item:any) => ({
                        value:item.roleCode,
                        label:item.roleName,
                        roleId:item.roleId
                    }))
                    setOptions(formattedOptions)
                } else {
                    message.error(`获取数据失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // 检查表单
    const checkForm = async () => {
        try {
            const values = await form.validateFields();
            console.log('验证通过:', values);
            const account = form.getFieldValue('account');
            const nickname = form.getFieldValue('nickname');
            const role = form.getFieldValue('role');
            const password = form.getFieldValue('password');
            const passwordCfm = form.getFieldValue('passwordCfm');
            if (!account) {
                message.error('请输入用户名');
                return;
            }
            if (!nickname) {
                message.error('请输入昵称');
                return;
            }
            if (!role) {
                message.error('请选择角色');
                return;
            }
            if (state === '1' && !password) {
                message.error('请输入登录密码');
                return;
            }
            if (state === '1' && !passwordCfm) {
                message.error('请再次输入密码');
                return;
            }
            if (state === '1' && password !== passwordCfm) {
                message.error('两次密码输入不一致');
                return;
            }
            state === '1' ?subAddAdmin():subUpdate()
        }catch(error){
            console.log(error)
            error.errorFields.map((item:any) => {
                message.error(item.errors[0])
            })
            // message.error(error?.errorFields[0].errors[0]);
        }

    }

    // 提交添加
    const subAddAdmin = async () => {
        setLoading(true)
        try {
            const passwordParam = md5(form.getFieldValue('password'))
            const response = await addStaff({
                account:form.getFieldValue('account'),
                nickname:form.getFieldValue('nickname'),
                password:passwordParam,
                roleId:handleRoleId,
                status:form.getFieldValue('status') === true?1:2,
                desc:form.getFieldValue('desc'),
            });
            if (response || response.data) {
                if (response?.errCode === 0) {
                    message.success('员工添加成功')
                    form.resetFields(); 
                    navigate('/setting/enterpriseManage/staffManage')
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // 提交修改
    const subUpdate = async () => {
        setLoading(true)
        try {
            const response = await updateStaffInfo({
                userId:userID,
                account:form.getFieldValue('account'),
                nickname:form.getFieldValue('nickname'),
                roleId:handleRoleId,
                roleCode:roleValue || defaultUserRole,
                status:form.getFieldValue('status') === true?1:2,
            });
            if (response || response.data) {
                if (response?.errCode === 0) {
                    message.success('员工修改成功')
                    form.resetFields()
                    navigate('/setting/enterpriseManage/staffManage')
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                }
            } else {
                message.error('响应数据格式错误');
            }
        } catch (error) {
            console.error('Error:', error);
        } finally {
            setLoading(false)
        }
    }

    // useEffect(() => {

    // }, []);

    useEffect(() => {
        if(state == '1'){
            searchRole()
        }else if(state == '2'){
            searchStaff(); 
        }
    }, []); 

    useEffect(() => {
        form.setFieldsValue({ account: defaultAccount });
        form.setFieldsValue({ nickname: defaultNickName });
        form.setFieldsValue({ status: defaultUserStatus });
        form.setFieldsValue({ role: defaultUserRole });
    }, [defaultAccount]);

    const tabsItems = [
        {
            label: '基本信息',
            key: '1',
            children: (
            <div style={{maxWidth: '455px'}}>
                <Form form={form} initialValues={{ status: true }}>
                    <Form.Item name="account" label="用户名" rules={[{required: true, message: '请输入用户名'},{ min: 4, message: '用户名至少需要4个字符' },{ max: 20, message: '用户名最多20个字符' }]}>
                        <Input allowClear placeholder="请输入用户名"/>
                    </Form.Item>
                    <Form.Item name="nickname" label="昵称" rules={[{required: true, message: '请输入昵称'},{ max: 20, message: '昵称最多20个字符' }]}>
                        <Input allowClear placeholder="请输入昵称"/>
                    </Form.Item>
                    <Form.Item name="role" label="角色" rules={[{required: true, message: '请选择角色'}]}>
                        <Select allowClear placeholder="请选择角色" options={options} onChange={roleChange} loading={loading}/>
                    </Form.Item>
                    {/* <Form.Item name="note4" label="个人简介">
                        <TextArea rows={4} maxLength={200} placeholder="请输入您的个人简介，最多不超过200字。"/>
                    </Form.Item> */}
                    <Form.Item name="status" label="状态" valuePropName="checked">
                        <Switch checkedChildren="正常" unCheckedChildren="禁用"/>
                    </Form.Item>
                </Form>
            </div>),
        },
        {
            label: '安全设置',
            key: '2',
            children: (
            <div>
                {(showPwd || state == '1') ? (
                    <div>
                        <Form.Item style={{ maxWidth: '455px' }} name="password" label="登录密码" rules={[{ required: true, message: '请输入登录密码' },{ min: 8, message: '密码至少需要8个字符' },{ max: 20, message: '密码最多20个字符' }]}>
                            <Input.Password placeholder="请输入登录密码" />
                        </Form.Item>
                        <Form.Item style={{ maxWidth: '455px' }} name="passwordCfm" label="确认密码" rules={[{ required: true, message: '请再次输入密码' },{ min: 8, message: '密码至少需要8个字符' },{ max: 20, message: '密码最多20个字符' }]}>
                            <Input.Password placeholder="请再次输入密码" />
                        </Form.Item>
                    </div>
                ) : (
                    <Flex justify="space-between">
                        <div style={{ color: '#999', marginLeft: '42px' }}>
                        密码已设置。密码至少8位字符，支持数字、字母和除空格外的特殊字符，且必须同时包含数字和大小写字母。
                        </div>
                        {state === '3' && (
                        <div style={{ color: '#165DFF', cursor: 'pointer', marginRight: '66px' }} onClick={() => { setShowPwd(true); }}>
                            修改
                        </div>
                        )}
                    </Flex>
                )}
            </div>
            ),
        }
    ]
    return (
        <div>
        {contextHolder}
        <Spin spinning={loading} fullscreen size='large'/>
        { state === '2' && (
        <div className={layout.userInfo}>
            <div className={layout.userPhoto}>
                <img src={reactSvg} className={layout.photo}/>
                <img src={uploadPhotoIcon} className={layout.photoIcon}/>
            </div>
            <div className={layout.InfoBox}>
                <div className={layout.formView}>
                    <div className={layout.formItem}>
                        <div className={layout.formLabel}>账号:</div>
                        <div className={layout.formValue}>{defaultAccount}</div>
                    </div>
                    <div className={layout.formItem}>
                        <div className={layout.formLabel}>ID:</div>
                        <div className={layout.formValue}>{userID}</div>
                    </div>
                    <div className={layout.formItem}>
                        <div className={layout.formLabel}>角色:</div>
                        <div className={layout.formValue}>{defaultUserRoleName}</div>
                    </div>
                </div>
                <div className={layout.formView}>
                    <div className={layout.formItem}>
                        <div className={layout.formLabel}>状态:</div>
                        <div className={layout.formValue}>{defaultUserStatusTxt === 1?'正常':'禁用'}</div>
                    </div>
                    <div className={layout.formItem}>
                        <div className={layout.formLabel}>最近登录时间:</div>
                        <div className={layout.formValue}>{latestLoginTime}</div>
                    </div>
                    <div className={layout.formItem}>
                        <div className={layout.formLabel}></div>
                        <div className={layout.formValue}></div>
                    </div>
                </div>
            </div>
        </div>
        )} 
        <div className={layout.formContent}>
            <Form form={form} className={layout.formView} labelAlign="right" labelCol={{ span: 6 }}>
                <Tabs defaultActiveKey="1" items={tabsItems}></Tabs>
            </Form>
        </div>
        <div className={layout.buttonView}>
            <Button type="primary" onClick={checkForm}>保存</Button>
            <Button style={{marginLeft: 10}} onClick={() => {
                navigate(-1)
            }}>返回</Button>
        </div>
        </div>
    )
}

export default StaffDetail